/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { BaseCommand, pickedFaceData, pickedLineData } from '@amcax/base';
import { previewer } from '@app-cad/module';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useMemo, useState } from 'react';
import { useCommand } from '@app-cad/common/hooks/useCommand';

type FormData = {
  profile: pickedLineData | pickedFaceData;
  spline: pickedLineData;
  axis: pickedLineData;
};

type SweepParams = {
  profile: string;
  spline: string;
  axis: string;
};

function RevolveSweep({
  title,
  onClose,
  placement,
  props,
}: CurvedCmdDialogParams) {
  const [formData, setFormData] = useState<FormData>({
    profile: null,
    spline: null,
    axis: null,
  });
  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({
        profile: null,
        spline: null,
        axis: null,
      });
      return;
    }

    const { profile, spline, axis } = props.params;

    await initEditDependency([profile, spline, axis]);

    const profileObj =
      profile &&
      (picker.generatePickObjByPickID(profile) as
        | pickedLineData
        | pickedFaceData);
    const splineObj =
      spline && (picker.generatePickObjByPickID(spline) as pickedLineData);
    const axisObj =
      axis && (picker.generatePickObjByPickID(axis) as pickedLineData);

    const datas = {
      profile: profileObj,
      spline: splineObj,
      axis: axisObj,
    };

    setFormData(datas);
  }, []);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) return;

    await execute();
    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, isLoading } =
    useCommand('cmd-revole-sweep', {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'CreateSurface',
      editDxid: props?.shape,
    });

  useAsyncEffect(async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }
    await execute(true);
  }, [formData]);

  const isFormDataValid = () => {
    const { profile, spline, axis } = formData;

    return profile != null && spline != null && axis != null;
  };

  const finishValid = useMemo(isFormDataValid, [formData]);

  const execute = async (preview: boolean = false) => {
    const { profile, spline, axis } = formData;
    const profileID: string = getIdOfPickedObj(profile);
    const splineID: string = getIdOfPickedObj(spline);
    const axisID: string = getIdOfPickedObj(axis);

    const params: SweepParams = {
      profile: profileID,
      spline: splineID,
      axis: axisID,
    };

    return await confirmCommand(
      {
        type: 'RotationSweep',
        a: params,
      },
      preview,
    );
  };

  const checkAndFinish = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute();

    exit();
  };

  const exit = () => {
    previewer.clear();
    onClose();
  };

  // =================

  const schema: RJSFSchema = {
    properties: {
      profile: {
        type: 'string',
        title: '轮廓',
        format: PickInputRJSFFormat.PickCurve,
      },
      spline: {
        type: 'string',
        title: '路径',
        format: PickInputRJSFFormat.PickCurve,
      },
      axis: {
        type: 'string',
        title: '旋转轴',
        format: PickInputRJSFFormat.PickLine,
      },
    },
  };

  return (
    <PickableCommandForm
      isFormDataValid={finishValid}
      disabled={initingEdit}
      submitLoading={isLoading}
      onClose={exit}
      title={title}
      placement={placement}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        profile: {
          'ui:placeholder': '请输入轮廓',
          'ui:autofocus': true,
        },
        spline: {
          'ui:placeholder': '请输入路径',
        },
        axis: {
          'ui:placeholder': '请输入旋转轴',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinish}
    />
  );
}

export const cmdRevolveSweep: BaseCommand = {
  id: 'cmdRevolveSweep',
  label: 'command.revolve-sweep',
  icon: 'commands/curved/revolve-sweep',
  create: (label, onClose, props) => (
    <RevolveSweep
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
